package cn.edu.henu.team.fragments;

import static cn.bmob.v3.Bmob.getApplicationContext;

import android.content.Context;
import android.content.Intent;
import android.util.Log;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.SimpleAdapter;
import android.widget.TextView;
import android.widget.Toast;

import androidx.annotation.NonNull;

import com.bumptech.glide.Glide;
import com.bumptech.glide.load.engine.DiskCacheStrategy;
import com.bumptech.glide.request.RequestOptions;
import com.geek.banner.Banner;
import com.geek.banner.loader.BannerEntry;
import com.nostra13.universalimageloader.core.DisplayImageOptions;
import com.nostra13.universalimageloader.core.ImageLoader;
import com.scwang.smart.refresh.footer.ClassicsFooter;
import com.scwang.smart.refresh.header.ClassicsHeader;
import com.scwang.smart.refresh.layout.SmartRefreshLayout;
import com.scwang.smart.refresh.layout.api.RefreshLayout;
import com.scwang.smart.refresh.layout.listener.OnLoadMoreListener;
import com.scwang.smart.refresh.layout.listener.OnRefreshListener;

import java.util.ArrayList;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;

import cn.bmob.v3.BmobQuery;
import cn.bmob.v3.exception.BmobException;
import cn.bmob.v3.listener.FindListener;
import cn.edu.henu.team.R;
import cn.edu.henu.team.base.BaseFragment;
import cn.edu.henu.team.bean.article_brief;
import cn.edu.henu.team.pageplug.BannerItem;
import cn.edu.henu.team.pageplug.mImageLoader;

import cn.edu.henu.team.ui.DetialActivity;

public class fragment1_article extends BaseFragment {

    private fragment1_article mContext;
    //文章列表
    private ArrayList<Map<String,Object>> mData = new ArrayList<>();
    private SimpleAdapter adapter=null;
    private ListView mListView;
    private DisplayImageOptions options; // 图片显示相关参数

    //banner
    private List<BannerItem> mpData = new ArrayList<>();
    private Banner banner;
    private SmartRefreshLayout refreshSrl;
    private TextView pagerTv;
    public static fragment1_article newInstance() {
        fragment1_article fragment = new fragment1_article();
        return fragment;
    }

    @Override
    protected void clickEvents() {
        mListView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                TextView t = (TextView) view.findViewById(R.id.objectId1);
                Intent it = new Intent(getActivity(), DetialActivity.class);
                it.putExtra("objectId", t.getText().toString());
                startActivity(it);
                adapter.notifyDataSetChanged();
            }
        });
    }

    @Override
    protected int initLayout() {
        return R.layout.fragement_1_article;
    }

    @Override
    protected void initView() {
        mContext = fragment1_article.this;
        mListView=mRootView.findViewById(R.id.alistview);

        // 使用DisplayImageOptions.Builder()创建DisplayImageOptions
        options = new DisplayImageOptions.Builder()
                .showImageOnLoading(R.mipmap.upload) // 设置图片下载期间显示的图片
                .showImageForEmptyUri(R.mipmap.upload) // 设置图片Uri为空或是错误的时候显示的图片
                .showImageOnFail(R.mipmap.upload) // 设置图片加载或解码过程中发生错误显示的图片
                .cacheInMemory(true) // 设置下载的图片是否缓存在内存中
                .cacheOnDisk(true) // 设置下载的图片是否缓存在SD卡中
                .build(); // 构建完成

        //banner设置
        banner = mRootView.findViewById(R.id.banner1);
        refreshSrl=mRootView.findViewById(R.id.refresh_srl);
        pagerTv = mRootView.findViewById(R.id.pager_tv);
        //banner
        mpData.add(new BannerItem(R.drawable.banner_1, ""));
        mpData.add(new BannerItem(R.drawable.banner_2, ""));
        mpData.add(new BannerItem(R.drawable.banner_3, ""));
        initBanner(banner);
        refreshSrl.setRefreshHeader(new ClassicsHeader(getApplicationContext()));
        refreshSrl.setRefreshFooter(new ClassicsFooter(getApplicationContext()));


        refreshSrl.setOnRefreshListener(new OnRefreshListener() {
            @Override
            public void onRefresh(@NonNull RefreshLayout refreshLayout) {
                refreshSrl.finishRefresh(1000/*,false*/);
                banner.loadImagePaths(mpData);
                initData();
            }
        });
        refreshSrl.setOnLoadMoreListener(new OnLoadMoreListener() {
            @Override
            public void onLoadMore(RefreshLayout refreshlayout) {
                refreshlayout.finishLoadMore(1000/*,false*/);//传入false表示加载失败
            }
        });
    }

    @Override
    protected void initData() {
        mData.clear();
        //list
        System.out.println("fragment1_article");
        BmobQuery<article_brief> bmobQuery = new BmobQuery("article_brief");
        bmobQuery.order("-createdAt");
        bmobQuery.findObjects(new FindListener<article_brief>() {
            @Override
            public void done(List<article_brief> list, BmobException e) {
                if (e==null)
                {
                    if(list!=null)
                    {
                        for (article_brief at:list)
                        {
                            Map<String,Object> temp = new LinkedHashMap<>();
                            temp.put("objectId",at.getObjectId());
                            temp.put("title",at.getTitle());
                            temp.put("info",at.getInfo());
                            temp.put("picture",at.getPicture());
                            mData.add(temp);
                        }
                        adapter=new SimpleAdapter(getApplicationContext(),mData,R.layout.article1_item,new String[]{"objectId","title","info","picture"},new int[]{R.id.objectId1,R.id.atitle,R.id.ainfo,R.id.apicture});
                        adapter.setViewBinder(new SimpleAdapter.ViewBinder() {
                            public boolean setViewValue(View view, Object data,
                                                        String textRepresentation) {
                                //判断是否为我们要处理的对象
                                if(view instanceof ImageView && data instanceof String){
                                    ImageView iv = (ImageView) view;
                                    ImageLoader.getInstance().displayImage((String) data, iv, options);
                                    return true;
                                }else
                                    return false;
                            }
                        });
                        mListView.setAdapter(adapter);
                        setListViewHeightBasedOnChildren();
                    }
                }else{

                }
            }
        });
    }
    //动态修改listview高度，使得listview能完全展开
    private void setListViewHeightBasedOnChildren() {
        if (mListView == null) {
            return;
        }
        if (adapter == null) {
            return;
        }
        int totalHeight = 0;
        //Toast.makeText(getApplication(), Integer.toString(simpleAdapter.getCount()), Toast.LENGTH_SHORT).show();
        for (int i = 0; i < mListView.getCount(); i++) {
            View listItem = adapter.getView(i, null, mListView);
            listItem.measure(0, 0);
            totalHeight += listItem.getMeasuredHeight();
        }
        ViewGroup.LayoutParams params = mListView.getLayoutParams();
        params.height = totalHeight + (mListView.getDividerHeight() * (adapter.getCount() - 1));
        mListView.setLayoutParams(params);
    }


    //banner
    private void initBanner(Banner banner) {
        // 1. 创建设置BannerLoader

        banner.setBannerLoader(new mImageLoader() {
            @Override
            public void loadView(Context context, BannerEntry entry, int position, View imageView) {

                if(position==1)
                {
                    pagerTv.setText(String.valueOf(position)+"/"+String.valueOf(mpData.size()));
                }
                else
                {
                    pagerTv.setText(String.valueOf(position+1)+"/"+String.valueOf(mpData.size()));
                }
                RequestOptions requestOptions = new RequestOptions()
                        .placeholder(R.drawable.banner_default)
                        .error(R.drawable.banner_default)
                        .diskCacheStrategy(DiskCacheStrategy.AUTOMATIC);
                Glide.with(context).load(entry.getBannerPath()).apply(requestOptions).into((ImageView) imageView);
            }
        });

        // 2 设置页面点击事件
        banner.setOnBannerClickListener(new Banner.OnBannerClickListener() {
            @Override
            public void onBannerClick(int position) {
                Toast.makeText(getApplicationContext(), "每天都要元气满满哦！", Toast.LENGTH_SHORT).show();
            }
        });

        // 3 翻页事件
        banner.setBannerPagerChangedListener(new Banner.OnBannerSimplePagerListener() {
            @Override
            public void onPageSelected(int position) {
                pagerTv.setText(String.valueOf(position+1)+"/"+String.valueOf(mpData.size()));
                Log.d("hsl777", "onPageSelected: ==>"
                        + position
                        + "\n" + banner);
            }
        });

        // 4 最重要一步，加载数据
        banner.loadImagePaths(mpData);
    }
    @Override
    public void onResume() {
        super.onResume();
        banner.startAutoPlay();
    }

    @Override
    public void onPause() {
        super.onPause();
        banner.stopAutoPlay();
    }


}
